<?php

namespace app\index\controller;

use app\common\controller\IndexBase;
use app\common\helper\WxHelper;
use app\common\model\User;

class Auth extends IndexBase
{
    public function auth()
    {
        $code = input('code','');
        if ($code) {
            $wx = new WxHelper();
            $info = $wx->codeToAccessToken($code)
                ->getUserInfo();
            $user = User::where('wx_openid',$info['openid'])->find();
            if (!$user) {
                $user = new User();
            }
            $user->headimgurl = $info['headimgurl'];
            $user->nick = $info['nickname'];
            $user->wx_openid = $info['openid'];
            $user->save();
            $u = User::find($user->id);
            session("user",$u);
            $url = url("Index/index",['archives_id'=>session('archives_id'),'share_user'=>session("share_user")]);
            $this->redirect(session('ref_url'));
        }
        return "^_^";
    }
}